package com.ninth_group.service.Impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ninth_group.constant.PCConstants;
import com.ninth_group.constant.WeatherCode;
import com.ninth_group.dao.PCDao;
import com.ninth_group.exception.province.ProvinceNameIsValidException;
import com.ninth_group.service.PCService;
import com.ninth_group.utils.ReuseCodeService;
import com.ninth_group.vo.ProvinceCitiesVO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class PCServiceImpl implements PCService {
    @Resource
    private PCDao pcDao;
    @Resource
    private ReuseCodeService reuseCodeService;

    /**
     * 获取该省下的所有市的天气信息
     * @param pName 省名称
     * @return List<ProvinceCitiesVO>
     */
    @Override
    public List<ProvinceCitiesVO> getPCWeatherInfo(String pName) throws JsonProcessingException {
        if (pName == null || pName.isEmpty())
            throw new ProvinceNameIsValidException("省份名称不能为空");

        // 获取redis缓存数据
        List<ProvinceCitiesVO> dataFromRedis = reuseCodeService.getDataFromRedis(
                PCConstants.ALL_WEATHER_DATA_FOR_PROVINCE + "_" + pName, ProvinceCitiesVO.class);

        // redis存在缓存
        if (!dataFromRedis.isEmpty()) return dataFromRedis;

        // 查询数据库并添加到redis中
        List<ProvinceCitiesVO> pcWeatherInfo = pcDao.getPCWeatherInfo(pName);

        // 给weatherCode赋值
        for (ProvinceCitiesVO vo : pcWeatherInfo) {
            vo.setWeatherCode(WeatherCode.getCodeByWeather(vo.getWeather()));
        }

        reuseCodeService.addToRedis(pcWeatherInfo,
                PCConstants.ALL_WEATHER_DATA_FOR_PROVINCE + "_" + pName,
                PCConstants.CACHE_TIME, TimeUnit.MINUTES);

        return pcWeatherInfo;
    }
}
